﻿using SmartSapce.ServiceLocation;
using SmartSpace.OA;
using SmartSpace.Web;
using SmartSpace.Workflow;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.WebApp.Modules.Workflow.Controls;

namespace SmartSpace.WebApp.Modules.OA.Pages
{
    public partial class LeaveRequest_Detail : SsTemplatePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Guid requestId = RequestUtility.GetGuid(this.Request, "id");
            ILeaveService service = ServiceLocator.Get<ILeaveService>();

            if (!IsPostBack)
            {
                LeaveRequest request = service.Get(requestId).Data;
                _ctlForm.DataSource = new LeaveRequest[] { request };
                _ctlForm.DataBind();
            }
        }

        void btn_Click(object sender, EventArgs e)
        {
            Guid requestId = RequestUtility.GetGuid(this.Request, "id");
            WFButton btn = sender as WFButton;
            Guid eventId = btn.WfEvent.Id;
            IWorkflowService wfService = ServiceLocator.Get<IWorkflowService>();
            WorkflowInstance instance = wfService.GetInstance("OA.LEAVE", requestId).Data;
            SingleResult<InstanceState> state = wfService.DriveInstance(instance.Id, eventId, requestId, "OA.LEAVE", User.Identity.Name, btn.SelectedUser);
            if (state.IsSuccess)
            {
                ILeaveService service = ServiceLocator.Get<ILeaveService>();
                SingleResult<LeaveRequest> leaveRequest = service.Get(requestId);
                leaveRequest.Data.StatusText = state.Data.StatusText;
                leaveRequest.Data.StatusCode = state.Data.StatusCode;
                service.Save(leaveRequest.Data);
                Response.Redirect("LeaveRequest-List.aspx");
            }
        }
    }
}